#include "threadPool.h"
#include "../log/log.h"

void thread_pool_init(thread_pool_t *pool, int worker_count)
{
    // 参数检查
    if (pool == NULL || worker_count <= 0)
    {
        // 记录错误日志
        LOG_ERROR("thread_pool_init: invalid arguments");
        exit(-1);
    }

    // 初始化线程池结构体
    bzero(pool, sizeof(thread_pool_t));
    // 先初始化共享资源
    pthread_mutex_init(&pool->shared_resource.mutex, NULL);
    pthread_cond_init(&pool->shared_resource.cond, NULL);
    pool->shared_resource.exit_flag = 0;
    task_queue_init(&pool->shared_resource.task_queue);
    // 再初始化工作线程列表
    workerList_init(&pool->worker_list, worker_count, &pool->shared_resource);

    return;
}

void thread_pool_release_workers(thread_pool_t *pool)
{
    // 参数检查
    if (pool == NULL)
    {
        // 记录错误日志
        LOG_ERROR("thread_pool_release_workers: invalid arguments");
        exit(-1);
    }

    // 设置退出标志
    pthread_mutex_lock(&pool->shared_resource.mutex);
    pool->shared_resource.exit_flag = 1;
    // 通知所有工作线程退出
    pthread_cond_broadcast(&pool->shared_resource.cond);
    pthread_mutex_unlock(&pool->shared_resource.mutex);
    // 等待所有工作线程退出
    for (int i = 0; i < pool->worker_list.worker_count; i++)
    {
        pthread_join(pool->worker_list.workers[i], NULL);
    }

    return;
}